<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brother PT-9500PC 标签设计器</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #1e3a8a;
            --secondary-color: #3b82f6;
            --accent-color: #0ea5e9;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --light-bg: #f8fafc;
            --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        body {
            background: linear-gradient(135deg, #e0f2fe 0%, #f0f9ff 100%) !important;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
            min-height: 100vh !important;
        }

        .page-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)) !important;
            color: white !important;
            padding: 2rem 0 !important;
            margin-bottom: 2rem !important;
            box-shadow: var(--card-shadow) !important;
        }

        .card {
            border: none !important;
            border-radius: 12px !important;
            box-shadow: var(--card-shadow) !important;
            transition: all 0.3s ease !important;
            background: white !important;
        }

        .card:hover {
            transform: translateY(-2px) !important;
            box-shadow: 0 8px 25px -5px rgba(0, 0, 0, 0.15) !important;
        }

        .field-card {
            cursor: pointer !important;
            transition: all 0.3s ease !important;
            border: 2px solid transparent !important;
        }

        .field-card:hover {
            border-color: var(--secondary-color) !important;
            background: linear-gradient(135deg, #f8fafc, #e0f2fe) !important;
        }

        .field-card.selected {
            border-color: var(--primary-color) !important;
            background: linear-gradient(135deg, #dbeafe, #bfdbfe) !important;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)) !important;
            border: none !important;
            border-radius: 8px !important;
            padding: 0.75rem 1.5rem !important;
            font-weight: 600 !important;
            transition: all 0.3s ease !important;
        }

        .btn-primary:hover {
            transform: translateY(-1px) !important;
            box-shadow: 0 4px 12px rgba(30, 58, 138, 0.4) !important;
        }

        .btn-outline-primary {
            border: 2px solid var(--secondary-color) !important;
            color: var(--secondary-color) !important;
            border-radius: 8px !important;
            font-weight: 600 !important;
        }

        .btn-outline-primary:hover {
            background: var(--secondary-color) !important;
            border-color: var(--secondary-color) !important;
        }

        .form-control, .form-select {
            border: 2px solid #e2e8f0 !important;
            border-radius: 8px !important;
            padding: 0.75rem 1rem !important;
            transition: all 0.3s ease !important;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-color) !important;
            box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25) !important;
        }

        .preview-area {
            background: white !important;
            border: 2px dashed #cbd5e1 !important;
            border-radius: 12px !important;
            min-height: 300px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            position: relative !important;
        }

        .label-preview {
            background: #f8fafc !important;
            border: 1px solid #cbd5e1 !important;
            border-radius: 4px !important;
            padding: 1rem !important;
            font-family: 'Courier New', monospace !important;
            font-size: 12px !important;
            line-height: 1.4 !important;
            white-space: pre-wrap !important;
            max-width: 100% !important;
            text-align: center !important;
        }

        .custom-field-item {
            background: #f1f5f9 !important;
            border: 1px solid #cbd5e1 !important;
            border-radius: 8px !important;
            padding: 1rem !important;
            margin-bottom: 0.5rem !important;
        }

        .section-title {
            color: var(--primary-color) !important;
            font-weight: 700 !important;
            margin-bottom: 1rem !important;
            padding-bottom: 0.5rem !important;
            border-bottom: 2px solid var(--secondary-color) !important;
        }

        .field-icon {
            width: 40px !important;
            height: 40px !important;
            background: linear-gradient(135deg, var(--accent-color), var(--secondary-color)) !important;
            border-radius: 50% !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            color: white !important;
            font-size: 1.2rem !important;
            margin-bottom: 0.75rem !important;
        }

        .alert {
            border: none !important;
            border-radius: 8px !important;
            font-weight: 500 !important;
        }

        .alert-info {
            background: linear-gradient(135deg, #dbeafe, #bfdbfe) !important;
            color: var(--primary-color) !important;
        }

        .breadcrumb {
            background: rgba(255, 255, 255, 0.9) !important;
            border-radius: 8px !important;
            padding: 0.75rem 1rem !important;
        }

        .breadcrumb-item a {
            color: var(--secondary-color) !important;
            text-decoration: none !important;
        }

        .breadcrumb-item.active {
            color: var(--primary-color) !important;
            font-weight: 600 !important;
        }

        @media (max-width: 768px) {
            .page-header {
                padding: 1rem 0 !important;
            }
            
            .card {
                margin-bottom: 1rem !important;
            }
            
            .field-card {
                text-align: center !important;
            }
        }
    </style>
</head>
<body>
    <div class="page-header">
        <div class="container">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-3">
                    <li class="breadcrumb-item"><a href="{% url 'assets:index' %}"><i class="fas fa-home"></i> 首页</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'assets:label_template_list' %}">标签模板</a></li>
                    <li class="breadcrumb-item active">Brother PT-9500PC 设计器</li>
                </ol>
            </nav>
            <h1 class="mb-0"><i class="fas fa-tag me-3"></i>Brother PT-9500PC 标签设计器</h1>
            <p class="mb-0 mt-2 opacity-75">设计和预览标签模板</p>
        </div>
    </div>

    <div class="container">
        <div class="row">
            <!-- 左侧配置面板 -->
            <div class="col-lg-4 mb-4">
                <div class="card h-100">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0"><i class="fas fa-cogs me-2"></i>标签配置</h5>
                    </div>
                    <div class="card-body">
                        <form id="labelForm">
                            {% csrf_token %}
                            
                            <!-- 基本设置 -->
                            <div class="mb-4">
                                <h6 class="section-title">基本设置</h6>
                                
                                <div class="mb-3">
                                    <label class="form-label">模板名称</label>
                                    <input type="text" class="form-control" id="templateName" 
                                           value="{% if template %}{{ template.name }}{% endif %}" 
                                           placeholder="输入模板名称" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">模板描述</label>
                                    <textarea class="form-control" id="templateDescription" rows="2" 
                                              placeholder="输入模板描述">{% if template %}{{ template.description }}{% endif %}</textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">标签宽度</label>
                                        <select class="form-select" id="labelWidth">
                                            <option value="6mm">6mm</option>
                                            <option value="9mm">9mm</option>
                                            <option value="12mm">12mm</option>
                                            <option value="18mm" selected>18mm</option>
                                            <option value="24mm">24mm</option>
                                            <option value="36mm">36mm</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">打印方向</label>
                                        <select class="form-select" id="orientation">
                                            <option value="portrait">纵向</option>
                                            <option value="landscape" selected>横向</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">字体大小</label>
                                    <select class="form-select" id="fontSize">
                                        <option value="small">小号</option>
                                        <option value="medium" selected>中号</option>
                                        <option value="large">大号</option>
                                    </select>
                                </div>
                            </div>

                            <!-- 字段选择 -->
                            <div class="mb-4">
                                <h6 class="section-title">字段选择</h6>
                                <div class="row g-2">
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="qr_code">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-qrcode"></i>
                                            </div>
                                            <small class="fw-bold">二维码</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="name">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-tag"></i>
                                            </div>
                                            <small class="fw-bold">资产名称</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="number">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-hashtag"></i>
                                            </div>
                                            <small class="fw-bold">资产编号</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="category">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-folder"></i>
                                            </div>
                                            <small class="fw-bold">资产类别</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="department">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-building"></i>
                                            </div>
                                            <small class="fw-bold">所属部门</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="user">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-user"></i>
                                            </div>
                                            <small class="fw-bold">使用人</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="location">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-map-marker-alt"></i>
                                            </div>
                                            <small class="fw-bold">存放位置</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="purchase_date">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-calendar"></i>
                                            </div>
                                            <small class="fw-bold">启用日期</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="warranty">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-shield-alt"></i>
                                            </div>
                                            <small class="fw-bold">保修期</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="serial_number">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-barcode"></i>
                                            </div>
                                            <small class="fw-bold">序列号</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="status">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-info-circle"></i>
                                            </div>
                                            <small class="fw-bold">资产状态</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="field-card card p-2 text-center" data-field="value">
                                            <div class="field-icon mx-auto">
                                                <i class="fas fa-dollar-sign"></i>
                                            </div>
                                            <small class="fw-bold">资产价值</small>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 基本信息字段 -->
                            <div class="mb-4">
                                <h6 class="section-title">基本信息</h6>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="includeCompanyHeader" {% if template and template.fields_config.company_header %}checked{% endif %}>
                                    <label class="form-check-label" for="includeCompanyHeader">
                                        <i class="fas fa-building me-1"></i>公司抬头
                                    </label>
                                </div>
                                <div class="mb-3">
                                    <input type="text" class="form-control form-control-sm" id="companyHeaderText"
                                           placeholder="请输入公司抬头，如：XX科技有限公司"
                                           value="{% if template %}{{ template.fields_config.company_header|default:'' }}{% endif %}">
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="includeLostNotice" {% if template and template.fields_config.lost_notice %}checked{% endif %}>
                                    <label class="form-check-label" for="includeLostNotice">
                                        <i class="fas fa-exclamation-triangle me-1"></i>遗失标签提示
                                    </label>
                                </div>
                                <div class="mt-2">
                                    <input type="text" class="form-control form-control-sm" id="lostNoticeText"
                                           placeholder="请输入遗失提示，如：如有遗失请联系 400-123-4567"
                                           value="{% if template %}{{ template.fields_config.lost_notice|default:'' }}{% endif %}">
                                </div>
                            </div>

                            <!-- 自定义字段 -->
                            <div class="mb-4">
                                <h6 class="section-title">自定义字段</h6>
                                <div id="customFields">
                                    <!-- 自定义字段将在这里动态添加 -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm w-100" id="addCustomField">
                                    <i class="fas fa-plus me-1"></i>添加自定义字段
                                </button>
                            </div>

                            <!-- 操作按钮 -->
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-primary" id="saveTemplate">
                                    <i class="fas fa-save me-2"></i>保存模板
                                </button>
                                <button type="button" class="btn btn-outline-primary" id="testPrint">
                                    <i class="fas fa-print me-2"></i>测试打印
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 右侧预览面板 -->
            <div class="col-lg-8">
                <div class="card h-100">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0"><i class="fas fa-eye me-2"></i>实时预览</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            选择左侧字段以查看标签预览效果。预览将根据您的选择实时更新。
                        </div>
                        
                        <div class="preview-area">
                            <div class="label-preview" id="labelPreview">
                                <div class="text-muted">
                                    <i class="fas fa-tag fa-3x mb-3"></i>
                                    <p>请选择要包含的字段</p>
                                    <small>标签预览将在此显示</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-3">
                            <small class="text-muted">
                                <i class="fas fa-lightbulb me-1"></i>
                                提示：点击左侧字段卡片来添加或移除字段，预览会实时更新
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 全局变量
        let selectedFields = new Set();
        let customFieldCounter = 0;
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeFieldSelection();
            initializeCustomFields();
            initializeFormHandlers();
            updatePreview();
        });
        
        // 字段选择初始化
        function initializeFieldSelection() {
            const fieldCards = document.querySelectorAll('.field-card');
            fieldCards.forEach(card => {
                card.addEventListener('click', function() {
                    const field = this.dataset.field;
                    if (selectedFields.has(field)) {
                        selectedFields.delete(field);
                        this.classList.remove('selected');
                    } else {
                        selectedFields.add(field);
                        this.classList.add('selected');
                    }
                    updatePreview();
                });
            });
        }
        
        // 自定义字段初始化
        function initializeCustomFields() {
            document.getElementById('addCustomField').addEventListener('click', function() {
                addCustomField();
            });
        }
        
        // 添加自定义字段
        function addCustomField(name = '', value = '') {
            customFieldCounter++;
            const customFieldsContainer = document.getElementById('customFields');
            const fieldHtml = `
                <div class="custom-field-item" data-field-id="${customFieldCounter}">
                    <div class="row g-2">
                        <div class="col-5">
                            <input type="text" class="form-control form-control-sm" 
                                   placeholder="字段名称" value="${name}">
                        </div>
                        <div class="col-5">
                            <input type="text" class="form-control form-control-sm" 
                                   placeholder="字段值" value="${value}">
                        </div>
                        <div class="col-2">
                            <button type="button" class="btn btn-outline-danger btn-sm w-100" 
                                    onclick="removeCustomField(${customFieldCounter})">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            customFieldsContainer.insertAdjacentHTML('beforeend', fieldHtml);
            updatePreview();
        }
        
        // 移除自定义字段
        function removeCustomField(fieldId) {
            const fieldElement = document.querySelector(`[data-field-id="${fieldId}"]`);
            if (fieldElement) {
                fieldElement.remove();
                updatePreview();
            }
        }
        
        // 表单处理初始化
        function initializeFormHandlers() {
            // 基本设置变化时更新预览
            const formControls = ['labelWidth', 'orientation', 'fontSize', 'includeCompanyHeader', 'includeLostNotice'];
            formControls.forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    element.addEventListener('change', updatePreview);
                }
            });
            // 文本输入实时更新
            const textInputs = ['companyHeaderText', 'lostNoticeText'];
            textInputs.forEach(id => {
                const el = document.getElementById(id);
                if (el) {
                    el.addEventListener('input', updatePreview);
                }
            });
            
            // 保存模板
            document.getElementById('saveTemplate').addEventListener('click', saveTemplate);
            
            // 测试打印
            document.getElementById('testPrint').addEventListener('click', testPrint);
        }
        
        // 更新预览
        function updatePreview() {
            const preview = document.getElementById('labelPreview');
            const labelWidth = document.getElementById('labelWidth').value;
            const orientation = document.getElementById('orientation').value;
            const fontSize = document.getElementById('fontSize').value;
            const includeCompanyHeader = document.getElementById('includeCompanyHeader').checked;
            const includeLostNotice = document.getElementById('includeLostNotice').checked;
            const companyHeaderText = (document.getElementById('companyHeaderText')?.value || '').trim();
            const lostNoticeText = (document.getElementById('lostNoticeText')?.value || '').trim();
            
            let previewContent = '';
            
            // 公司抬头
            if (includeCompanyHeader) {
                previewContent += (companyHeaderText || '【公司名称】') + '\n';
            }
            
            // 选中的字段
            if (selectedFields.size > 0) {
                const fieldLabels = {
                    'qr_code': '[QR码]',
                    'name': '资产名称: 示例设备',
                    'number': '资产编号: ASSET-001',
                    'category': '类别: 办公设备',
                    'department': '使用部门: 信息技术部',
                    'user': '使用人: 张三',
                    'location': '位置: A栋3楼',
                    'purchase_date': '启用日期: 2024-01-15',
                    'warranty': '保修: 2027-01-15',
                    'serial_number': '序列号: SN123456',
                    'status': '状态: 在用',
                    'value': '价值: ¥5,000'
                };
                
                selectedFields.forEach(field => {
                    if (fieldLabels[field]) {
                        previewContent += fieldLabels[field] + '\n';
                    }
                });
            }
            
            // 自定义字段
            const customFields = document.querySelectorAll('.custom-field-item');
            customFields.forEach(field => {
                const inputs = field.querySelectorAll('input');
                const name = inputs[0].value.trim();
                const value = inputs[1].value.trim();
                if (name && value) {
                    previewContent += `${name}: ${value}\n`;
                }
            });
            
            // 遗失标签提示
            if (includeLostNotice) {
                previewContent += '\n' + (lostNoticeText || '如有遗失请联系管理员');
            }
            
            // 更新预览显示
            if (previewContent.trim()) {
                preview.innerHTML = `<div style="font-size: ${getFontSize(fontSize)}; text-align: ${orientation === 'portrait' ? 'center' : 'left'};">${previewContent}</div>`;
            } else {
                preview.innerHTML = `
                    <div class="text-muted">
                        <i class="fas fa-tag fa-3x mb-3"></i>
                        <p>请选择要包含的字段</p>
                        <small>标签预览将在此显示</small>
                    </div>
                `;
            }
        }
        
        // 获取字体大小
        function getFontSize(size) {
            const sizes = {
                'small': '10px',
                'medium': '12px',
                'large': '14px'
            };
            return sizes[size] || '12px';
        }
        
        // 保存模板
        function saveTemplate() {
            const templateName = document.getElementById('templateName').value.trim();
            if (!templateName) {
                alert('请输入模板名称');
                return;
            }
            
            // 收集自定义字段
            const customFields = [];
            document.querySelectorAll('.custom-field-item').forEach(field => {
                const inputs = field.querySelectorAll('input');
                const name = inputs[0].value.trim();
                const value = inputs[1].value.trim();
                if (name && value) {
                    customFields.push({ name, value });
                }
            });
            
            const templateData = {
                name: templateName,
                description: document.getElementById('templateDescription').value.trim(),
                label_width: document.getElementById('labelWidth').value,
                orientation: document.getElementById('orientation').value,
                font_size: document.getElementById('fontSize').value,
                printer_model: 'pt-9500pc',
                selected_fields: Array.from(selectedFields),
                include_company_header: document.getElementById('includeCompanyHeader').checked,
                include_lost_notice: document.getElementById('includeLostNotice').checked,
                company_header: (document.getElementById('companyHeaderText')?.value || '').trim(),
                lost_notice: (document.getElementById('lostNoticeText')?.value || '').trim(),
                custom_fields: customFields
            };
            
            // 发送保存请求
            fetch('{% url "assets:save_label_template" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify(templateData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('模板保存成功！');
                } else {
                    alert('保存失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('保存错误:', error);
                alert('保存失败，请重试');
            });
        }
        
        // 测试打印
        function testPrint() {
            if (selectedFields.size === 0) {
                alert('请至少选择一个字段进行测试打印');
                return;
            }
            
            alert('测试打印功能将在后续版本中实现');
        }
    </script>
</body>
</html>
